'''
Created on Sep 4, 2011

@author: david
'''
from app.G6.actions import G6Action

class Update(G6Action):
    """
    Create or update a user account from
    form input.  Return is in JSON
    """
    def execute(self):
        import logging
        import json
        from app.G6.agents import AccountAgent
        
        req = self.request
        acct = rv = None
       
        # parse out params
        args = req.getParameters()
        mode = req.getParameter("mode","update")
        
        logging.debug("~~ Args: %s " % args)
        # create agent to do the work
        agent = AccountAgent()
        
        try:

            # check for create v. update
            if mode == 'new':
                # create new account
                logging.info("++ Creating new account for %s " % args['uid'])
                acct = agent.create(args)
                #req.session.setAttribute('acct',acct)
                
                rv = json.dumps({"results":"200::Ok","acct": acct.toJSON() })
            else:
                # validate session
                if not self.auth_check():
                    return self.JSONOutput(json.dumps({"results":"401::Invalid Session"}))
                else:
                    # get existing account from session 
                    acct = req.session.getAttribute(['acct'],None)
                    if not acct:
                        # this should not happen
                        rv = json.dumps({"results":"500::Invalid Account in Session!"})
                    else:
                        # all good    
                        agent.update(acct, args)
                        rv = json.dumps({"results":"200::Ok","acct": acct })
        except Exception,ex:
            logging.exception(str(ex))
            rv = json.dumps({"results":"500::Action Exception(%s)" % str(ex)}) 
                      
        # all done, send out the json
        return self.JSONOutput(rv)
